/**
 * Created by Administrator on 2017/5/8 0008.
 * 用户注册
 */
import {
    instance
} from '../../../src/Wap'
// 系统全局性变量
window.Wap = instance

$(function () {
    var $autoLogin = new Wap.autoLogin();
    // 自动登录并跳转
    $autoLogin.loging(function(rdata){
        if(rdata.code == 1){
            location.href = Wap._homeUrl+'#user';
        }
    });
    // 验证码刷新
    function reflushCode() {
        var img = $('#recode_lnk').find('img');
        // var src = img.attr("src");
        let src = '/captcha.jpg?image='+(Math.random()*100)
        // if(!src)
        img.attr('src',src);
    }
    /**
     * 登录记住
     * @param {Object} data
     * @param {Object} rdata 
     */
    function rememberRegister(data, rdata){
        if(rdata && rdata.remember && 'object' == typeof rdata.remember){
            var feek_token = (rdata && rdata.remember)? rdata.remember.feek_token || false : false;
            if(feek_token){
                $autoLogin.add({
                    rmbr_ftoken: feek_token,
                    account : data.account
                });
            }
        }
    }
    // 验证码更换
    $('#recode_lnk').click(function () { reflushCode(); });
   // 登录数据提交
    var SubmitForm = function(){
        weui.form.validate('.js__form', function (error) {
            if (!error) {
                var loading = instance.weuiLoading('登录中...');
                var savedata = Wap.formJson('.js__form');
                Wap.ApiRequest('login/auth',savedata,function (data) {
                    loading.hide();
                    if(data.code == -1){
                        weui.alert(data.msg);
                        reflushCode();
                        return;
                    }
                    rememberRegister(savedata, data);
                    setTimeout(function () {
                        location.href = Wap._homeUrl+'#user';
                    },3000);
                    weui.toast('登录成功',2000);
                    weui.loading('页面跳转中...');
                });
                /*
                setTimeout(function () {
                    loading.hide();
                    weui.toast('提交成功', 3000);
                }, 1500);
                */
            }
            // return true; // 当return true时，不会显示错误
        });
    };
    // 表单检测
    weui.form.checkIfBlur('.js__form');
    $('#save_lnk').click(function () {
        SubmitForm();
    });
    //  键盘事件绑定
    $(document).keydown(function(event){
        //console.log(evt);
        switch(event.keyCode){
            case 13:    // Enter
                SubmitForm();
                break;
        }
    });
});
